import { useState, useEffect, useCallback, useRef } from 'react';

// 默认固定元素高度配置
const defaultFixedElements = {
  header: 64,           // Layout头部
  cardHeader: 57,       // Card头部
  tableHeader: 55,      // 表格头部
  pagination: 64,       // 分页器
  cardPadding: 24,      // Card内边距 (上下各12px)
  contentPadding: 40,   // content-container的padding (上16px + 下24px)
  spaceBetween: 24,     // 搜索表单和表格之间的间距 (space-y-6)
};

// 高度配置选项
export interface HeightOptions {
  offset?: number;           // 额外偏移量
  minHeight?: number;        // 最小高度
  maxHeight?: number;        // 最大高度
  searchFormSelector?: string; // 搜索框选择器
}

// 返回的尺寸信息
export interface TableDimensions {
  tableHeight: number;      // 表格滚动区域高度
  containerHeight: number;  // 容器总高度
  searchFormHeight: number; // 搜索框实际高度
}

// 创建一个全局事件发射器用于布局变化通知
let layoutChangeListeners: (() => void)[] = [];

export const triggerLayoutChange = () => {
  layoutChangeListeners.forEach(listener => listener());
};

export const useAdaptiveTableHeight = (
  options: HeightOptions = {}
): TableDimensions => {
  const {
    offset = 10,
    minHeight = 450,
    maxHeight,
    searchFormSelector = '.search-form-card'
  } = options;

  const [dimensions, setDimensions] = useState<TableDimensions>({
    tableHeight: minHeight,
    containerHeight: 500,
    searchFormHeight: 80
  });

  const timeoutRef = useRef<number>();

  // 动态获取搜索框高度
  const getSearchFormHeight = useCallback(() => {
    const searchForm = document.querySelector(searchFormSelector);
    if (searchForm) {
      const rect = searchForm.getBoundingClientRect();
      // 搜索框高度 + 底部间距
      return Math.ceil(rect.height) + 16;
    }
    // 默认搜索框高度（单行时）
    return 88;
  }, [searchFormSelector]);

  const calculateDimensions = useCallback(() => {
    // 防抖处理
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    timeoutRef.current = setTimeout(() => {
      const viewportHeight = window.innerHeight;
      
      // 动态获取搜索框实际高度
      const searchFormHeight = getSearchFormHeight();
      
      // 计算页面级固定元素高度（包含动态搜索框高度）
      const pageFixedHeight = defaultFixedElements.header + 
                              defaultFixedElements.contentPadding + 
                              searchFormHeight + 
                              defaultFixedElements.spaceBetween;
      
      // 计算可用高度
      let availableHeight = viewportHeight - pageFixedHeight - offset;
      
      // 应用最小和最大高度限制
      if (availableHeight < minHeight) {
        availableHeight = minHeight;
      }
      
      if (maxHeight && availableHeight > maxHeight) {
        availableHeight = maxHeight;
      }

      // 计算表格滚动区域的实际高度
      // 需要减去：Card头部 + 表格头部 + 分页器 + Card内边距
      const tableInternalHeight = defaultFixedElements.cardHeader + 
                                  defaultFixedElements.tableHeader + 
                                  defaultFixedElements.pagination + 
                                  defaultFixedElements.cardPadding;
      
      const tableScrollHeight = Math.floor(availableHeight - tableInternalHeight);
      const containerHeight = Math.floor(availableHeight);

      setDimensions({
        tableHeight: Math.max(tableScrollHeight, 250), // 降低最小表格滚动区域高度
        containerHeight: Math.max(containerHeight, 350), // 降低最小容器高度
        searchFormHeight
      });
    }, 100); // 100ms防抖
  }, [offset, minHeight, maxHeight, getSearchFormHeight]);

  useEffect(() => {
    // 初始计算
    calculateDimensions();

    // 窗口大小变化监听
    const handleResize = () => {
      calculateDimensions();
    };

    // 布局变化监听（侧边栏收起/展开）
    const handleLayoutChange = () => {
      // 延迟执行，等待DOM更新完成
      setTimeout(calculateDimensions, 150);
    };

    // DOM变化监听（搜索框内容变化）
    const observer = new MutationObserver(() => {
      calculateDimensions();
    });

    const searchForm = document.querySelector(searchFormSelector);
    if (searchForm) {
      observer.observe(searchForm, {
        childList: true,
        subtree: true,
        attributes: true
      });
    }

    // 添加事件监听器
    window.addEventListener('resize', handleResize);
    layoutChangeListeners.push(handleLayoutChange);

    // 清理函数
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
      window.removeEventListener('resize', handleResize);
      layoutChangeListeners = layoutChangeListeners.filter(listener => listener !== handleLayoutChange);
      observer.disconnect();
    };
  }, [calculateDimensions, searchFormSelector]);

  return dimensions;
}; 